package com.example.netcamerastreamdemo;

import android.media.MediaDataSource;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlMediaDataSource extends MediaDataSource {
    private static final String TAG = "UrlMediaDataSource";

    URL mUrl;
    HttpURLConnection connection;
    BufferedInputStream stream;

    public UrlMediaDataSource(String url) {
        try {
            this.mUrl = new URL(url);
            connection = (HttpURLConnection) mUrl.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int readAt(long l, byte[] bytes, int i, int i1) throws IOException {
        if (stream == null) {
            stream = new BufferedInputStream(connection.getInputStream());
        }
        return stream.read(bytes, i, i1);
    }

    @Override
    public long getSize() throws IOException {
        return 0;
    }

    @Override
    public void close() throws IOException {
        stream.close();
        stream = null;
        connection.disconnect();
        connection = null;
    }
}
